<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>

      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            class="input-with-select"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList()"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button @click="crrr()">添加用户</el-button>
        </el-col>
      </el-row>

      <el-table
        :data="UserList"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="index"></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
        >
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
        >
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
        >
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色"
        >
        </el-table-column>
        <!-- 自定义插槽 -->
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userState(scope.row)"
            >
            </el-switch>
          </template>

        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="修改"
              placement="top"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="chaUser(scope.row),dialogVisible = true"
              ></el-button>
            </el-tooltip>

            <!-- 删除 -->

            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top"
            >

              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="deleteUser(scope.row)"
              ></el-button>

            </el-tooltip>
            <!--  -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-star-off"
                circle
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>
      <!-- //分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 4, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户 -->
    <el-card
      class="box-card"
      v-show="create"
    >
      <el-form
        :model="createUser"
        :rules="rules"
        ref="createUser"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="用户名"
          prop="username"
        >
          <el-input v-model="createUser.username"></el-input>
        </el-form-item>
        <el-form-item
          label="用户密码"
          prop="password"
        >
          <el-input v-model="createUser.password"></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input v-model="createUser.email"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
        >
          <el-input v-model="createUser.mobile"></el-input>
        </el-form-item>
        <el-button
          type="primary"
          @click="submitForm('createUser')"
        >创建</el-button>
        <el-button @click="resetForm('createUser')">重置</el-button>
      </el-form>
    </el-card>
    <!-- 修改用户 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-form
        ref="form"
        :rules="editFormRules"
        :model="UsersLlll"
        label-width="80px"
      >
        <el-form-item
          label="用户名"
          prop="username"
        >
          <el-input
            v-model="UsersLlll.username"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input v-model="UsersLlll.email"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
        >
          <el-input v-model="UsersLlll.mobile"></el-input>
        </el-form-item>

      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="xiugaiUser(),dialogVisible=false"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog
      title="提示"
      :visible.sync="xxx"
      width="50%"
    >
      <div>
        <p>当前用户：{{userInfo.username}}</p>
        <p>当前角色:{{userInfo.role_name}}</p>
        分配角色:<el-select
          v-model="value"
          placeholder="请选择"
        >
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="xxx = false">取 消</el-button>
        <el-button
          type="primary"
          @click="updateRoles()"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      userInfo: {},
      xxx: false,
      input: "",
      dialogVisible: false,
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      UserList: {},
      UsersLlll: {},
      total: 0,
      createUser: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      create: false,
      rules: {
        username: [
          { required: true, message: "请输入賬號", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      editFormRules: {
        email: [{ required: true, message: "请修改邮箱", trigger: "blur" }],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            min: 11,
            max: 11,
            message: "长度在11个字符",
            trigger: "blur",
          },
        ],
      },
      rolesList: {},
      value:'',
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    //创建用户
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await this.$http.post("users", this.createUser);
          console.log(res.data);
          this.getUserList();
          this.$message.success("创建成功");
          this.crrr();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    crrr() {
      this.create = !this.create;
    },
    //获取用户
    async getUserList() {
      const res = await this.$http.get("users", { params: this.queryInfo });
      if (res.data.meta.status !== 200) return this.$message.error("获取失败");
      // console.log(res.data.data.users);
      this.UserList = res.data.data.users;
      this.total = res.data.data.total;
      // console.log(this.UserList);
    },
    //根据id查用户
    async chaUser(userInfo) {
      const res = await this.$http.get(`users/${userInfo.id}`);
      // console.log(res.data);
      this.UsersLlll = res.data.data;
    },
    //修改用户
    async xiugaiUser() {
      const res = await this.$http.put("users/" + this.UsersLlll.id, {
        email: this.UsersLlll.email,
        mobile: this.UsersLlll.mobile,
      });
      // console.log(res.data);
      if (res.data.meta.status !== 200) return this.$message.error("获取失败");
      this.$message.success("更新成功");
      this.getUserList();
    },
    //删除用户
    deleteUser(userInfo) {
      this.$confirm("此操作将删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$http.delete(`users/${userInfo.id}`);
          console.log(res.data);
          this.getUserList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //分配角色
    async setRole(userInfo) {
      this.userInfo = userInfo;

      const res = await this.$http.get("roles");
      if (res.data.meta.status !== 200) return this.$message.error("获取失败");
      this.rolesList = res.data.data;
      this.xxx = true;
    },

    //更新角色权限 updateRoles
    async updateRoles(){
        if(!this.value){
          return this.$message.error('未分配角色')
        }
      const res =await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.value})
      if (res.data.meta.status !== 200) return this.$message.error("更新失败");
      this.$message.success('更新成功')
         this.getUserList();
        this.xxx=false
    },

    //每页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.queryInfo.pagesize = val;
      this.getUserList();
    },
    //第几页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.queryInfo.pagenum = val;
      this.getUserList();
    },
    //改状态
    async userState(userInfo) {
      // console.log(userInfo);

      const res = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      if (res.data.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        this.$message.error("更新用户状态失败");
      }
    },
  },
};
</script>

<style scoped>
.el-card {
  margin-top: 15px;
}

.el-table {
  margin-top: 15px;
}
.el-pagination {
  margin-top: 15px;
}
</style>
